package sn.gandal.mobile.kalpet.guichet;

import sn.gandal.mobile.kalpet.persistence.Account;
import sn.gandal.mobile.kalpet.persistence.Credentials;

import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 * Created by IntelliJ IDEA.
 * User: SOWDIOMYERO
 * Date: 17 juin 2012
 * Time: 04:53:50
 * To change this template use File | Settings | File Templates.
 */
@WebService()
public class GuichetService {

    @PersistenceContext(unitName = "guichet")
    EntityManager em;
    @Resource
    UserTransaction utx;

    public GuichetService() {
    }

    @WebMethod(operationName = "authUser")
    public boolean getAuthUser(
            @WebParam(name = "numeroClient") String numeroClient,
            @WebParam(name = "codeSecret") String codeSecret){
       Integer numCli=Integer.parseInt(numeroClient);
       Integer code=Integer.parseInt(codeSecret);
       Account account=null;
       try{

           Query query=em.createNamedQuery("Account.findByNumeroClientAndCodeSecret");
           query.setParameter("numeroClient",numCli);
           query.setParameter("codeSecret",code);
           account= (Account)query.getSingleResult();
           if(account !=null)
               return true;
           else
               return false;

          } catch (Exception e) {
           return false;
       }
         // return account;


    }

    @WebMethod(operationName = "addAccount")
    public Account addAccount(
            @WebParam(name = "account") Account account,
            @WebParam(name = "password") Credentials credentials)  {
     try{
         
        utx.begin();
        em.persist(account);
        credentials.setAccount(account);
        em.persist(credentials);
        em.flush();

            utx.commit();
        } catch (Exception e) {
         try {
             utx.rollback();
         } catch (SystemException e1) {
             //do nothing
         }
     }
        return account;

    }

     @WebMethod(operationName = "getAccount")
    public Account getAccount(
            @WebParam(name = "nom") String nom,
            @WebParam(name = "prenom") String prenom)  {
         Account account=null;
     try{

         Query query=em.createNamedQuery("Account.findByPrenom");
         query.setParameter("prenom",prenom);
         account= (Account)query.getSingleResult();

        } catch (Exception e) {
         try {
             utx.rollback();
         } catch (SystemException e1) {
             //do nothing
         }
     }
        return account;

    }
}
